﻿using EasyCore.UnifyResult.Exceptions;
using EasyCore.UnifyResult.Results;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasyCore.UnifyResult.Filters
{
    /// <summary>
    ///捕获 方法、只捕获 MVC 管道中的异常（控制器、Action 过滤器、模型绑定等）
    /// </summary>
    public class ApiExceptionFilter : IAsyncExceptionFilter
    {
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            try {
                if (context.ExceptionHandled)
                {
                    return;
                }
                switch (context.Exception)
                {
                    case BusinessException: //业务异常
                        var ex = context.Exception as BusinessException;
                        context.Result = new ObjectResult(new EasyApiResult((int)EasyStatusCodes.OperateBusinessException, ex.Message));
                        break;
                    default: //其他日志
                        context.Result = new ObjectResult(new EasyApiResult((int)EasyStatusCodes.ApplicationException, "系统异常，请查看操作日志！"));
                        break;
                }
                context.ExceptionHandled = true;
            } catch (Exception ex) { } finally {
                await Task.CompletedTask;
            }  
        }
    }
}
